package com.iclippi.client;

import java.util.ArrayList;

import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.RichTextArea;
import com.google.gwt.user.client.ui.VerticalPanel;

public class Editor extends Composite {

	public interface AutosaveHandler{
		public void onAutosave();
	}
	
	private VerticalPanel editorPanel = new VerticalPanel();
	private RichTextArea editorArea	= new RichTextArea();
	private RichTextToolbar toolbar;
	private Timer autosaveTimer;
	private boolean dirty = false;
	
	
	private ArrayList<AutosaveHandler> autosaveHandlers = new ArrayList<AutosaveHandler>();
	
	public void addAutosaveHandler(AutosaveHandler handler){
		autosaveHandlers.add(handler);
		
	}
	
	public void removeAutosaveHandler(AutosaveHandler handler){
		autosaveHandlers.remove(handler);
	} 
	
	public Editor(){
		editorPanel.setStylePrimaryName("editor");
		toolbar = new RichTextToolbar(editorArea);
		editorPanel.add(toolbar);
		editorPanel.add(editorArea);
		
		autosaveTimer=new Timer() {
			@Override
			public void run() {
				for (AutosaveHandler handler:autosaveHandlers) 
					handler.onAutosave();
			}
		};
	

		editorArea.addKeyUpHandler(new KeyUpHandler() {
			@Override
			public void onKeyUp(KeyUpEvent event) {
				// Wait for user to stop clicking on the keyboard, in order to try to autosave
				autosaveTimer.cancel();
				autosaveTimer.schedule(3000);
				
				// Set dirty
				dirty=true;
			}
		});
		
		initWidget(editorPanel);
	}
	
	public void setDirty(boolean flag){
		dirty=flag;
	}
	
	public boolean getDirty(){
		return dirty;
	}
	
	public void adjustSize(int width, int height){
		int panelHeight=height-8;
		int panelWidth=width-8;
		if (panelHeight<1) panelHeight=1;
		if (panelWidth<1) panelWidth=1;
		editorPanel.setHeight(panelHeight+"px");
		editorPanel.setWidth(panelWidth+"px");
		
		int editorHeight=panelHeight-toolbar.getOffsetHeight()-1;
		int editorWidth=panelWidth-1;
		if (editorHeight<1) editorHeight=1;
		if (editorWidth<1) editorWidth=1;
		editorArea.setHeight(editorHeight+"px");
		editorArea.setWidth(editorWidth+"px");
	}
	
	public String getEditorValue(){
		return editorArea.getHTML();
	}
	
	public void setEditorValue(String html){
		editorArea.setHTML(html);
	}
}
